export default async function buildTree(meterData) {
    // 输入验证
    if (!Array.isArray(meterData)) {
        throw new Error('输入必须是数组类型');
    }

    // 分块处理机制防止卡死
    const CHUNK_SIZE = 100;
    const processInChunks = (data, processFn) => {
        const results = [];
        for (let i = 0; i < data.length; i += CHUNK_SIZE) {
            const chunk = data.slice(i, i + CHUNK_SIZE);
            results.push(...processFn(chunk));
            // 让UI线程有机会响应
            if (i + CHUNK_SIZE < data.length) {
                setTimeout(() => { }, 0);
            }
        }
        return results;
    };

    try {
        const idMapping = new Map();
        const treeData = [];

        // 分块处理节点
        processInChunks(meterData, (chunk) => {
            chunk.forEach(meter => {
                if (!meter.id) {
                    console.warn(`跳过无效的表计(缺少ID)`, meter);
                    return;
                }

                try {
                    idMapping.set(meter.id, {
                        ...meter,
                        label: `${meter.meter_code || '未知'} ${meter.meter_name ? '(' + meter.meter_name + ')' : ''}`,
                        children: [],
                        level: 1 // 初始默认level为1，后续会根据父子关系更新
                    });
                } catch (err) {
                    console.error(`处理表计${meter.id}时出错:`, err);
                }
            });
            return [];
        });

        // 建立父子关系并更新level
        const updateNodeLevels = (node, level) => {
            node.level = level;
            if (node.children?.length) {
                node.children.forEach(child => updateNodeLevels(child, level + 1));
            }
        };

        for (const [id, node] of idMapping) {
            try {
                const parentId = node.parent_id;
                if (!parentId || !idMapping.has(parentId)) {
                    treeData.push(node);
                } else {
                    const parent = idMapping.get(parentId);
                    if (parent) {
                        parent.children.push(node);
                    } else {
                        console.warn(`未找到节点${id}的父节点${parentId}`);
                        treeData.push(node);
                    }
                }
            } catch (err) {
                console.error(`建立节点${id}关系时出错:`, err);
            }
        }

        // 更新所有根节点的level层级
        treeData.forEach(node => updateNodeLevels(node, 1));

        // 排序带超时保护
        const getSortNum = code => {
            if (!code) return 999999;
            const match = code.match(/-(\d+)$/);
            return match ? +match[1] : 999999;
        };

        const sortWithTimeout = (nodes, timeout = 5000) => {
            return new Promise((resolve, reject) => {
                const timeoutId = setTimeout(() => {
                    reject(new Error('排序超时'));
                }, timeout);

                try {
                    nodes.sort((a, b) => getSortNum(a.meter_code) - getSortNum(b.meter_code));
                    nodes.forEach(node => {
                        if (node.children?.length) {
                            sortWithTimeout(node.children);
                        }
                    });
                    clearTimeout(timeoutId);
                    resolve();
                } catch (err) {
                    clearTimeout(timeoutId);
                    reject(err);
                }
            });
        };

        // 执行排序
        try {
            await sortWithTimeout(treeData);
        } catch (err) {
            console.error('排序出错:', err);
            // 排序失败时返回未排序数据
        }

        return treeData;

    } catch (err) {
        console.error('构建树结构时发生严重错误:', err);
        // 构建失败时返回原始数据，确保包含level字段
        return meterData.map(meter => ({
            ...meter,
            label: `${meter.meter_code || '未知'} (${meter.id})`,
            children: [],
            level: 1
        }));
    }
}